package com.ddwl.order.dao;

import com.ddwl.common.constant.BaseEnum;
import com.ddwl.common.dao.TkDao;
import com.ddwl.common.util.MySqlUtil;
import com.ddwl.order.dao.mapper.SeckillMapper;
import com.ddwl.order.dao.model.Seckill;
import com.ddwl.schema.bo.order.QuerySeckillBo;
import com.ddwl.schema.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.time.Instant;
import java.util.List;

/**
 * (Seckill)表数据库访问层
 *
 * @author wenbin
 */
@Slf4j
@Repository
public class SeckillDao extends TkDao<SeckillMapper, Seckill> {

    /**
     * 查询秒杀活动列表
     * @return
     */
    public List<Seckill> querySeckillList(QuerySeckillBo bo){
        Example example = getExample();
        example.and().andEqualTo("id",bo.getSeckillId())
                .andLike("seckillName", MySqlUtil.allLike(bo.getSeckillName()))
                .andEqualTo("isEffect",bo.getIsEffect())
                .andEqualTo("isDist",bo.getIsDist())
                .andGreaterThanOrEqualTo("startTime",bo.getStartTime())
                .andLessThanOrEqualTo("endTime",bo.getEndTime())
                .andLessThanOrEqualTo("startTime",bo.getTime())
                .andGreaterThanOrEqualTo("endTime",bo.getTime())
        ;
        if (bo.getTime()!=null){
            example.setOrderByClause(" start_time");
        }

        List<Seckill> seckills = baseMapper.selectByExample(example);
        return seckills;
    }

    /**
     * 查询最近的秒杀活动
     * @return
     */
    public Seckill getRecentSeckill(){
        Instant time = Instant.now();
        Example example = new Example(Seckill.class);
        example.and().andLessThanOrEqualTo("startTime", time)
                .andGreaterThanOrEqualTo("endTime", time)
                .andEqualTo("isEffect", 1);

        example.or().andGreaterThanOrEqualTo("startTime",time)
                .andEqualTo("dflag", BaseEnum.DflagEnum.NOT_DELETE.getCode())
                .andEqualTo("isEffect",1)
                .andLessThan("startTime", DateUtil.getTimesNight());
        example.setOrderByClause(" start_time");

        List<Seckill> seckills = baseMapper.selectByExampleAndRowBounds(example,new RowBounds(0,1));
        if(!CollectionUtils.isEmpty(seckills)){
            return seckills.get(0);
        }
        return null;
    }


}